package org.kwin.tomcat.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpRequest;
import org.kwin.tomcat.servlet.http.HttpServlet;
import org.kwin.tomcat.servlet.http.HttpServletRequest;
import org.kwin.tomcat.servlet.http.HttpServletResponse;

import java.util.Map;

/**
 * @author : wangkai
 * @version V1.0
 * @Package org.kwin.tomcat.handler
 * @Description:
 * @date 2021年10月12日 9:37
 **/
@ChannelHandler.Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<HttpRequest> {
    private final Map<String, HttpServlet> servletMapping;
    
    public HttpRequestHandler(Map<String, HttpServlet> servletMapping) {
        this.servletMapping = servletMapping;
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        cause.printStackTrace();
        ctx.close();
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req)
        throws Exception {
        HttpServletRequest request = new HttpServletRequest(req);
        HttpServletResponse response = new HttpServletResponse(ctx, req);
        String url = request.getUrl();
        try {
            // 先看是否有对应的servlet处理
            for(String urlPattern : servletMapping.keySet()) {
                if(url.startsWith(urlPattern.replaceAll("\\*", ""))) {
                    servletMapping.get(urlPattern).service(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(ctx.channel().isOpen()) {
                ctx.flush();
                ctx.close();
            }
        }
    }
}
